package com.springapp.mvc.dao;

import com.springapp.mvc.entity.Group;
import com.springapp.mvc.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by nkrivko on 19.12.2014.
 */
@Component
public class RoleDaoImpl  implements RoleDao{

    @Autowired
    private JdbcTemplate template;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.template = template;
    }

    @Override
    public Role getRoleById(long id) {
        String q = "SELECT * FROM roles WHERE id = ?";
        List<Role> result = template.query(q,  Mappers.ROLE_MAPPER, id);
        return result.isEmpty() ? null : result.get(0);
    }

    @Override
    public List<Group> getGroupsByRoleId(Long roleId) {
        String q = "SELECT * FROM roles r " +
                   "INNER JOIN group_role gr ON r.id = gr.role_id " +
                   "INNER JOIN groups g      ON g.id = gr.group_id "+
                   "WHERE r.id = ?";
        return template.query(q, Mappers.GROUP_MAPPER, roleId);
    }

    @Override
    public long createRole(String roleName) {
        template.update("INSERT INTO roles (name) values (?)", roleName);
        return template.queryForLong("select last_insert_id()");
    }

    @Override
    public Role getRoleByName(String name) {
        String q = "SELECT * FROM roles WHERE name = ?";
        List<Role> result = template.query(q, Mappers.ROLE_MAPPER, name);
        return result.isEmpty() ? null : result.get(0);
    }

    @Override
    public List<Role> getAllRoles() {
        return template.query("SELECT * FROM groups", Mappers.ROLE_MAPPER);
    }
}
